package com.example.demo.ImgTest;


import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class CompressPicTest {

    public static void main(String[] args) throws IOException {
        // 原始图片路径
        String originalPath = "C:/Users/FF998/Pictures/Camera Roll/图片/bg.jpg";

        // 目标图片保存路径及文件名
        String compressedPath = "C:/Users/FF998/Pictures/Camera Roll/图片/aaa.jpg";

        // 设置压缩后的图片大小（像素）
//        int targetWidth = 800;
//        int targetHeight = 600;


        // 创建BufferedImage对象并加载原始图片
        BufferedImage image = ImageIO.read(new File(originalPath));

        int targetWidth = image.getWidth();
        int targetHeight = image.getHeight();

        // 计算压缩比例
        double scaleX = (double)targetWidth / image.getWidth();
        double scaleY = (double)targetHeight / image.getHeight();
        double scaleFactor = Math.min(scaleX, scaleY);

        // 根据压缩比例调整图片大小
        AffineTransform transform = new AffineTransform();
        transform.setToScale(scaleFactor, scaleFactor);
        AffineTransformOp op = new AffineTransformOp(transform, null);
        image = op.filter(image, null);

        // 将压缩后的图片保存到指定位置
        ImageIO.write(image, "jpeg", new File(compressedPath));

        System.out.println("图片压缩完成！");
    }
}
